package com.isoft.service.impl;

import com.isoft.entity.DfmeDlyeEntity;
import com.isoft.mapper.DfmeDlyeMapper;
import com.isoft.service.DfmeDlyeService;
import com.isoft.util.XmlParserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Service
public class DfmeDlyeServiceImpl implements DfmeDlyeService {
    private static final Logger logger = LoggerFactory.getLogger(DfmeDlyeServiceImpl.class);

    @Autowired
    private DfmeDlyeMapper dfmeDlyeMapper;

    @Autowired
    private XmlParserUtil xmlParserUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(MultipartFile file) throws IOException {
        String xmlContent = new String(file.getBytes(), StandardCharsets.UTF_8);
        logger.info("Processing DFME-DLYE XML file: {}, size: {} bytes",
                file.getOriginalFilename(), file.getSize());
        return parseAndSave(xmlContent);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void parseAndSave(DfmeDlyeEntity entity) {
        processFlightData(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(String xmlContent) {
        try {
            if (xmlContent == null || xmlContent.trim().isEmpty()) {
                throw new IllegalArgumentException("XML content is empty");
            }

            DfmeDlyeEntity entity = xmlParserUtil.parseXml(xmlContent, DfmeDlyeEntity.class);

            if (entity == null || entity.getDflt() == null) {
                throw new IllegalArgumentException("Invalid XML structure");
            }

            // 1. 先插入FLIGHT_BASE记录
            try {
                dfmeDlyeMapper.insertFlightBase(entity);
            } catch (org.springframework.dao.DataIntegrityViolationException ex) {
                if (ex.getMessage() != null && ex.getMessage().contains("唯一性约束")) {
                    logger.warn("DFME-DLYE 航班ID已存在，跳过插入: {}", entity.getDflt().getFlightId());
                    return "DFME-DLYE Flight already exists, skipped. Flight ID: " + entity.getDflt().getFlightId();
                } else {
                    throw ex;
                }
            }

            // 2. 插入MSG_META记录
            dfmeDlyeMapper.insertMeta(entity);

            // 3. 插入FLIGHT_IRREGULARITY记录
            dfmeDlyeMapper.insertFlightIrregularity(entity);

            // 4. 最后插入FLIGHT_ROUTE记录
            dfmeDlyeMapper.insertFlightRoute(entity);

            return "DFME-DLYE data processed successfully. Flight ID: " + entity.getDflt().getFlightId();
        } catch (Exception e) {
            logger.error("DFME-DLYE XML processing failed", e);
            throw new RuntimeException("Failed to process DFME-DLYE XML: " + e.getMessage());
        }
    }

    private void processFlightData(DfmeDlyeEntity entity) {
        dfmeDlyeMapper.insertMeta(entity);
        dfmeDlyeMapper.insertFlightIrregularity(entity);
        dfmeDlyeMapper.insertFlightRoute(entity);
    }
}